/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hos_ahmedadeltito.photoeditorsdk.utils;

import ohos.aafwk.ability.DataAbilityHelper;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DragInfo;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.PixelMapHolder;
import ohos.agp.render.Texture;
import ohos.app.Context;
import ohos.data.rdb.ValuesBucket;
import ohos.media.image.ImagePacker;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Optional;

/**
 * PixelMap位图处理工具
 *
 * @since 2021-05-10
 */
public class PixelMapUtil {
    /**
     * 图片保存路径
     */
    public static final String DCIM_PATH = "/storage/emulated/0/DCIM/";

    private static PixelMap componentChangeToPixelMap(Component mComponent) {
        // TODO 把component转换为PiexlMap
        PixelMap.InitializationOptions initializationOptions = new PixelMap.InitializationOptions();
        initializationOptions.size = new Size(mComponent.getWidth(), mComponent.getHeight());
        initializationOptions.pixelFormat = PixelFormat.ARGB_8888;
        Canvas canvas = new Canvas();
        PixelMap pixelMap = PixelMap.create(initializationOptions);
        return null;
    }

    /**
     * mergePixelMap
     *
     * @param drawPixelMap
     * @param imgPixelMap
     * @return Optional
     */
    public static Optional<PixelMap> mergePixelMap(PixelMap drawPixelMap, PixelMap imgPixelMap) {
        if (drawPixelMap != null) {
            if (imgPixelMap == null || drawPixelMap == null) return Optional.empty();
            PixelMap.InitializationOptions opt = new PixelMap.InitializationOptions();
            opt.editable = true;
            opt.size = new Size(imgPixelMap.getImageInfo().size.width, imgPixelMap.getImageInfo().size.height);
            opt.pixelFormat = PixelFormat.ARGB_8888;
            PixelMap pixelMap3 = PixelMap.create(imgPixelMap, opt);
            Texture texture = new Texture(pixelMap3);
            Canvas canvas = new Canvas(texture);
            PixelMapHolder pixelMapHolder = new PixelMapHolder(drawPixelMap);
            canvas.drawPixelMapHolder(pixelMapHolder, 0, 0, new Paint());
            canvas.restore();
            canvas = null;
            return Optional.ofNullable(pixelMap3);
        }
        return Optional.empty();
    }

    /**
     * 保存图片
     *
     * @param context 上下文
     * @param fileName 保存路径
     * @param pixelMap 需要保存的位图
     * @return 保存后的uri
     */
    public static Uri savePixelMap(Context context, String fileName, PixelMap pixelMap) {
        if (fileName == null || fileName.isEmpty()) {
            fileName = String.valueOf(System.currentTimeMillis());
        }
        try {
            ValuesBucket valuesBucket = new ValuesBucket();
            valuesBucket.putString(AVStorage.Images.Media.DISPLAY_NAME, fileName);
            valuesBucket.putString("relative_path", "DCIM/");
            valuesBucket.putString(AVStorage.Images.Media.MIME_TYPE, "image/" + "jpeg");
            //应用独占
            valuesBucket.putInteger("is_pending", 1);
            DataAbilityHelper helper = DataAbilityHelper.creator(context.getApplicationContext());
            int id = helper.insert(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, valuesBucket);
            Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, String.valueOf(id));
            //这里需要"w"写权限
            FileDescriptor fd = helper.openFile(uri, "w");
            ImagePacker imagePacker = ImagePacker.create();
            ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();
            OutputStream outputStream = new FileOutputStream(fd);
//            packingOptions.format = mCompressFormat;
            packingOptions.quality = 90;
            boolean result = imagePacker.initializePacking(outputStream, packingOptions);
            if (result) {
                result = imagePacker.addImage(pixelMap);
                if (result) {
                    long dataSize = imagePacker.finalizePacking();
                }
            }
            outputStream.flush();
            outputStream.close();
            valuesBucket.clear();
            //解除独占
            valuesBucket.putInteger("is_pending", 0);
            helper.update(uri, valuesBucket, null);
            return uri;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
